package com.farmer.service.impl;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farmer.mapper.UserMapper;

import com.farmer.pojo.Goods;
import com.farmer.pojo.Orders;
import com.farmer.pojo.Poorapply;
import com.farmer.pojo.User;
import com.farmer.service.PoorapplyService;
import com.farmer.mapper.PoorapplyMapper;
import com.farmer.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

/**
* @author 86183
* @description 针对表【poorapply(贫困户申请表)】的数据库操作Service实现
* @createDate 2024-05-02 21:35:36
*/
@Service
public class PoorapplyServiceImpl extends ServiceImpl<PoorapplyMapper, Poorapply>
    implements PoorapplyService{


    @Autowired
    private PoorapplyMapper poorapplyMapper;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OSS ossClient;

    private final String bucketName = "pgh1118";
    @Override
    public Result add(String token, Poorapply poorapply) {
        int userid = jwtHelper.getUserId(token).intValue();
        User user = userMapper.selectById(userid);
        poorapply.setUserId(userid);
        poorapply.setUserName(user.getName());
        poorapply.setTime(DateFormat.getDateInstance().format(new Date()));
        poorapplyMapper.insert(poorapply);
        return Result.ok(null);
    }


    @Override
    public Result delete(Integer id) {
       poorapplyMapper.deleteById(id);
        return null;
    }


    @Override
    public Result update(Poorapply poorapply) {
        poorapplyMapper.updateById(poorapply);
//        如果审核通过，需要把用户的身份改成贫困户
        if("审核通过".equals(poorapply.getStatus())){
            User user = userMapper.selectById(poorapply.getUserId());
            if (user!=null){
                user.setLevel(LevelEnum.POOR.level);
                userMapper.updateById(user);
            }
        }
        return Result.ok(null);
    }


    @Override
    public Result getById(Integer id) {
       Poorapply poorapply = poorapplyMapper.selectById(id);
        if (poorapply != null) {
            return Result.build(poorapply, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

//    @Override
//    public Result getByUserId(Integer id){
//
//    }
    @Override
    public Result getAll() {
        List<Poorapply> poorapplies = poorapplyMapper.selectList(null);
        if (poorapplies != null && !poorapplies.isEmpty()) {
            return Result.build(poorapplies, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }
    @Override
    public Result getPoorapplyListByToken(String token) {
        // 验证token的有效性
        int userId = jwtHelper.getUserId(token).intValue();
        LambdaQueryWrapper<Poorapply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Poorapply::getUserId, userId);
        // 根据用户ID获取订单列表
        List<Poorapply> poorapplyList = poorapplyMapper.selectList(lambdaQueryWrapper);
        if (poorapplyList != null && !poorapplyList.isEmpty()) {
            return Result.build(poorapplyList, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

    @Override
    public Result getByTitleLike(String status){
        LambdaQueryWrapper<Poorapply> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Poorapply::getStatus,status);
        List<Poorapply> poorapplys = poorapplyMapper.selectList(lambdaQueryWrapper);
        if (poorapplys!=null&&!poorapplys.isEmpty()){
            return Result.build(poorapplys,111,"查询成功");
        }else{
            return Result.build(null,101,"未找到匹配信息");
        }
    }


/*
* 上传文件*/
    @Override
    public Result uploadFile(Integer id, MultipartFile file)  {
        try {
            String url = Upload.uploadImage(file);
            Poorapply poorapply = poorapplyMapper.selectById(id);
            poorapply.setId(id);
            poorapply.setFile(url);
            updateById(poorapply);
            return Result.build(url, ResultCodeEnum.SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.build(null, ResultCodeEnum.FAULT);
        }
        }
/*
* 下载文件*/
//   @Override
//    public InputStream downloadFile(Integer id) {
//       Poorapply poorapply =poorapplyMapper.selectById(id);
//       String fileName = poorapply.getFile();
//       System.out.println(fileName);
//        try {
//            if (ossClient.doesObjectExist(bucketName,fileName)) {
//                OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, fileName));
//                return ossObject.getObjectContent();
//            } else {
//                return null;
//            }
//        } catch (Exception e) {
//            // 记录错误或处理异常
//            throw new RuntimeException("下载文件失败", e);
//        }
//
//    }

    /*
     * 分页查询*/
    @Override
    public Result page(Integer pageNum, Integer pageSize){
        // 创建分页构造对象
        Page<Poorapply> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<Poorapply> result = poorapplyMapper.selectPage(page, null);
        // 封装到统一响应体Result中
        return Result.ok(result);
    }


    }





